﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
using System.IO;

namespace WinFormUIXMLParser
{
    public static class StaticTypes
    {
        public static List<Font> listFonts = new List<Font>();

        public static Dictionary<string, Image> DicImages = new Dictionary<string, Image>();

        public static string ButtonImageFolder = "";

        public static string IconFolder = "";

        public static string FormBKGFolder = "";

        public static string PageGifFolder = "";

        public static string KeyboardFolder = "";

        public static string VoiceFolder = "";

        public static string XmlConfigFolder = "";

        static StaticTypes()
        {
            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            directory = directory.Substring(6);
            //DirectoryInfo dllDirectory = new DirectoryInfo(directory);
            //DirectoryInfo baseDir = dllDirectory.Parent.Parent;
            ButtonImageFolder = directory + @"\images\button\";
            IconFolder = directory + @"\images\icon\";
            FormBKGFolder = directory + @"\images\window\";
            PageGifFolder = directory + @"\images\gif\";
            KeyboardFolder = directory + @"\keyboard\";
            VoiceFolder = directory + @"\voice\";
            XmlConfigFolder = directory + @"\Config\";
        }


        /// <summary>  
        /// 生成反射过来的MethodInfo到指定类型的委托  
        /// </summary>  
        /// <typeparam name="T">EventArgs泛型类型</typeparam>  
        /// <param name="instance">当前对象</param>  
        /// <param name="method">需要转化为delegate的方法</param>  
        /// <returns></returns>  
        public static EventHandler<T> CreateDelegateFromMethodInfo<T>(Object instance, MethodInfo method) where T : EventArgs//约束泛型T只能是来自EventArgs类型的  
        {    
            Delegate del = Delegate.CreateDelegate(typeof(EventHandler<T>), instance, method);  
            EventHandler<T> mymethod = del as EventHandler<T>;  
            return mymethod;  
        }  
  
        /// <summary>  
        /// 生成反射过来的MethodInfo到指定类型的委托  
        /// </summary>  
        /// <typeparam name="T">EventHandle泛型类型</typeparam>  
        /// <param name="instance">当前对象</param>  
        /// <param name="method">需要转化为delegate的方法</param>  
        /// <returns></returns>  
        public static EventHandler CreateDelegateFromMethodInfoByDelegate<T>(Object instance, MethodInfo method)  
        {    
            Delegate del = Delegate.CreateDelegate(typeof(T), instance, method);  
            EventHandler mymethod = del as EventHandler;  
            return mymethod;  
        }

        public static Size GetSize(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return Size.Empty;
            }
            string realVal = value;
            if (value.Contains("C") && value.Contains(")"))
            {
                int begin = value.IndexOf("(");
                int end = value.IndexOf(")");
                realVal = value.Substring(begin + 1, end - begin - 1);
            }         
            string[] arr = realVal.Split(',');
            if (arr.Length == 2)
            {
                int w = Convert.ToInt32(arr[0]);
                int h = Convert.ToInt32(arr[1]);
                return new Size(w, h);
            }
            return Size.Empty;
        }

        public static bool ConvertToBoolean(string tStr, bool defaultVal = true)
        {
            if (string.IsNullOrEmpty(tStr))
            {
                return defaultVal;
            }
            bool value = defaultVal;
            bool.TryParse(tStr, out value);
            return value;
        }

        public static Color GetColor(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return Color.Empty;
            }
            value = value.Trim();
            if (value.Contains("(") && value.Contains(")"))
            {
                int begin = value.IndexOf("(");
                int end = value.IndexOf(")");
                string realVal = value.Substring(begin + 1, end - begin - 1);
                string[] arr = realVal.Split(',');
                if (arr.Length == 3)
                {
                    int r = Convert.ToInt32(arr[0]);
                    int g = Convert.ToInt32(arr[1]);
                    int b = Convert.ToInt32(arr[2]);
                    return Color.FromArgb(r, g, b);
                }
                if (arr.Length == 4)
                {
                    int a = Convert.ToInt32(arr[0]);
                    int r = Convert.ToInt32(arr[1]);
                    int g = Convert.ToInt32(arr[2]);
                    int b = Convert.ToInt32(arr[3]);
                    return Color.FromArgb(a, r, g, b);
                }
            }
            if (!value.Contains(","))
            {
                Type colorType = typeof(Color);
                PropertyInfo info = colorType.GetProperty(value, BindingFlags.Public | BindingFlags.Static);
                if (info != null)
                {
                    return (Color)info.GetValue(null, null);
                }

                Type colorType1 = typeof(System.Drawing.SystemColors);
                PropertyInfo info1 = colorType1.GetProperty(value, BindingFlags.Public | BindingFlags.Static);
                if (info1 != null)
                {
                    return (Color)info1.GetValue(null, null);
                }
            }
            else
            {
                string[] array = value.Split(',');
                if (array.Length == 3)
                {
                    int r = Convert.ToInt32(array[0]);
                    int g = Convert.ToInt32(array[1]);
                    int b = Convert.ToInt32(array[2]);
                    return Color.FromArgb(r, g, b);
                }
            }
            return Color.Empty;
        }

        private static Font GetFont(string[] values)
        {
            string fontName = values[0];
            string fontSize = values[1];
            if (fontSize.EndsWith("F") || fontSize.EndsWith("f"))
            {
                fontSize = fontSize.Substring(0, fontSize.Length - 1);
            }
            float fontsize = float.Parse(fontSize);
            FontStyle style = FontStyle.Regular;
            if (values.Length == 3)
            {
                string fontStyle = values[2];
                style = (FontStyle)Enum.Parse(typeof(FontStyle), fontStyle);
            }
            Font ff = listFonts.Find(r => r.Name.Equals(fontName) && r.Size == fontsize && r.Style == style);
            if (ff == null)
            {
                return new Font(fontName, fontsize, style);
            }
            else
            {
                return ff;
            }          
        }

        public static Font GetFont(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            if (value.Contains("(") && value.Contains(")"))
            {
                int begin = value.IndexOf("(");
                int end = value.IndexOf(")");
                string realVal = value.Substring(begin + 1, end - begin - 1);
                string[] arr = realVal.Split(',');
                if (arr.Length == 3 || arr.Length == 2)
                {
                    return GetFont(arr);
                }
            }
            string[] array = value.Split(',');
            if (array.Length == 3 || array.Length == 2)
            {
                return GetFont(array);
            }             
            return null;
        }

        private static Point GetLocation(string[] values)
        {
            int x = Convert.ToInt32(values[0]);
            int y = Convert.ToInt32(values[1]);
            return new Point(x, y);
        }

        public static Point GetLocation(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return Point.Empty;
            }
            if (value.Contains("(") && value.Contains(")"))
            {
                int begin = value.IndexOf("(");
                int end = value.IndexOf(")");
                string realVal = value.Substring(begin + 1, end - begin - 1);
                string[] arr = realVal.Split(',');
                if (arr.Length == 2)
                {
                    return GetLocation(arr);
                }
            }
            string[] array = value.Split(',');
            if (array.Length == 2)
            {
                return GetLocation(array);
            }
            return Point.Empty;
        }

        public static Image GetImage(string file)
        {
            if (DicImages.ContainsKey(file))
            {
                return DicImages[file];
            }
            if (File.Exists(file))
            {
                Image image = Image.FromFile(file);
                DicImages.Add(file, image);
                return image;
            }
            return null;
        }

        public static Image GetButtonImage(string value)
        {
            string file = Path.Combine(ButtonImageFolder, value);
            return GetImage(file);
        }

        public static Image GetWindowImage(string value)
        {
            string file = Path.Combine(FormBKGFolder, value);
            return GetImage(file);        
        }

        public static Image GetPageGifImage(string value)
        {
            string file = Path.Combine(PageGifFolder, value);
            return GetImage(file);        
        }

        public static Image GetIconImage(string value)
        {
            string file = Path.Combine(IconFolder, value);
            return GetImage(file);
        }
    }
}

 
  //      /// <summary>
  //      /// 清空控件的事件列表
  //      /// </summary>
  //      /// <param name="pControl">要清空事件列表的控件</param>
  //      /// <param name="pEventName">事件名</param>
  //      public static void GetEventHandle(Control pControl, string pEventName)
  //      {
  //          if (pControl == null)
  //              return;
  //          if (string.IsNullOrEmpty(pEventName)) return;
  //          BindingFlags mPropertyFlags = BindingFlags.Instance | BindingFlags.Public
  //              | BindingFlags.Static | BindingFlags.NonPublic;//筛选
  //          BindingFlags mFieldFlags = BindingFlags.Static | BindingFlags.NonPublic;
  //          Type controlType = typeof(System.Windows.Forms.Control);
  //          PropertyInfo propertyInfo = controlType.GetProperty("Events", mPropertyFlags);
  //          EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(pControl, null);//事件列表
  //          FieldInfo fieldInfo = (typeof(Control)).GetField("Event" + pEventName, mFieldFlags);
  //          Delegate d = eventHandlerList[fieldInfo.GetValue(pControl)];
  //          if (d == null) return;
  //          EventInfo eventInfo = controlType.GetEvent(pEventName);
  //          foreach (Delegate dx in d.GetInvocationList())
  //          {
  //              eventInfo.RemoveEventHandler(pControl, dx);//移除已订阅的pEventName类型事件
  //          }
  //      }

  //      public static void GetMethod()
  //      {
  //          string strClass = "Test";           // 命名空间+类名
  //          string strMethod = "Method";        // 方法名
  //          Type type;                          // 存储类
  //          Object obj;                         // 存储类的实例
  //          type = Type.GetType(strClass);      // 通过类名获取同名类
  //          obj = System.Activator.CreateInstance(type);       // 创建实例
  //          MethodInfo method = type.GetMethod(strMethod, new Type[] { });      // 获取方法信息
  //          object[] parameters = null;
  //          method.Invoke(obj, parameters);                           // 调用方法，参数为空
  //          // 注意获取重载方法，需要指定参数类型
  //          method = type.GetMethod(strMethod, new Type[] { typeof(string) });      // 获取方法信息
  //          parameters = new object[] { "hello" };
  //          method.Invoke(obj, parameters);                             // 调用方法，有参数
  //          method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });      // 获取方法信息
  //          parameters = new object[] { "hello", "你好" };
  //          string result = (string)method.Invoke(obj, parameters);     // 调用方法，有参数，有返回值
  //      }

 //var type = "^#[0-9a-fA-F]{6}{1}$" ;  
 //   var re = new RegExp(type);  
 //   if (colorValue.match(re) == null) {  
 //       type = "^[rR][gG][Bb][\(]((2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?),){2}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)[\)]{1}$";  
